<template>
<div id="container"> 
</div>
</template>

<script setup lang="ts"> 
import * as THREE from 'three';
import { onMounted } from 'vue';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';


onMounted(()=>{
    let isCarCamera = false;

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0,80,50);
    camera.lookAt(0,0,0);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById("container")?.appendChild(renderer.domElement);
    renderer.setClearColor(0x000000);

    const light = new THREE.AmbientLight(0xffffff);
    scene.add(light);

    //地面
    const ground = new THREE.PlaneGeometry(100, 100);
    const groundMaterial = new THREE.MeshPhongMaterial({color: 0xcc8866, side: THREE.DoubleSide});
    const groundMesh = new THREE.Mesh(ground, groundMaterial);
    groundMesh.rotation.x = -Math.PI / 2; //默认是z=0平面，沿着x轴旋转90度
    scene.add(groundMesh);

    const controls = new OrbitControls(camera, renderer.domElement);

    
    //路线
    const curve = new THREE.SplineCurve([
        new THREE.Vector2(25,-25),
        new THREE.Vector2(25,0),
        new THREE.Vector2(-25,0),
        new THREE.Vector2(-25,25),
        new THREE.Vector2(0,25),
        new THREE.Vector2(0,-25),
        new THREE.Vector2(-25,-25),
        new THREE.Vector2(-25,0),
        new THREE.Vector2(25,0),
        new THREE.Vector2(25,25),
        new THREE.Vector2(0,25),
        new THREE.Vector2(0,-25),
        new THREE.Vector2(25,-25),
    ]);

    const points = curve.getPoints(1000);
    const geometry = new THREE.BufferGeometry().setFromPoints(points);
    const material = new THREE.LineBasicMaterial({ color: 0xff0000 });
    const line = new THREE.Line(geometry, material);
    line.rotateX(-Math.PI / 2);
    line.translateZ(.1);
    scene.add(line);


    //car
    const car = new THREE.Object3D();
    scene.add(car);
    const carCamera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
    carCamera.position.set(0, 10, -10);
    car.add(carCamera);

    //主体
    const carGeomtry = new THREE.BoxGeometry(5, 5, 2);
    const carMaterial = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
    const body = new THREE.Mesh(carGeomtry, carMaterial);
    body.rotation.x = -Math.PI / 2;
    // body.position.set(25,1.1,25);
    car.add(body);
    //轮子
    const wheelRadius = 2;
    const wheelThickness = 0.5;
    const wheelSegments = 6;
    const wheelGeometry = new THREE.CylinderGeometry(
        wheelRadius,
        wheelRadius,
        wheelThickness,
        wheelSegments
    );
    const wheelMaterial = new THREE.MeshPhongMaterial({ color: 0x888888 });
    
    const wheelList:THREE.Mesh[] = [];

    const wheel1 = new THREE.Mesh(wheelGeometry, wheelMaterial);
    wheel1.rotation.x = Math.PI / 2;
    wheel1.rotation.z = Math.PI / 2;
    wheel1.position.z = -2.5;
    wheel1.position.x = -3;
    car.add(wheel1);

    const wheel2 = new THREE.Mesh(wheelGeometry, wheelMaterial);
    wheel2.rotation.x = Math.PI / 2;
    wheel2.rotation.z = Math.PI / 2;
    wheel2.position.z = -2.5;
    wheel2.position.x = 3;
    car.add(wheel2);

    const wheel3 = new THREE.Mesh(wheelGeometry, wheelMaterial);
    wheel3.rotation.x = Math.PI / 2;
    wheel3.rotation.z = Math.PI / 2;
    wheel3.position.z = 2.5;
    wheel3.position.x = -3;
    car.add(wheel3);

    const wheel4 = new THREE.Mesh(wheelGeometry, wheelMaterial);
    wheel4.rotation.x = Math.PI / 2;
    wheel4.rotation.z = Math.PI / 2;
    wheel4.position.z = 2.5;
    wheel4.position.x = 3;
    car.add(wheel4);

    wheelList.push(wheel1, wheel2, wheel3, wheel4);
    // car.position.set(25,2,25);



    const resizeRendererToDisplaySize = (renderer: any) => {
        const canvas = renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        const needResize = canvas.width !== width || canvas.height !== height;
        if (needResize) {
            renderer.setSize(width, height, false);
        }

        return needResize;
    };

    const carPosition = new THREE.Vector2();
	const carTarget = new THREE.Vector2();

    const render = (time:number) => {
        if (resizeRendererToDisplaySize( renderer )){
            const canvas = renderer.domElement;
            camera.aspect = canvas.clientWidth / canvas.clientHeight;
            camera.updateProjectionMatrix();
            carCamera.aspect = canvas.clientWidth / canvas.clientHeight;
            carCamera.updateProjectionMatrix();
        }
        wheelList.forEach(wheel=>{
            wheel.rotation.x +=0.1;
        })

        const carTime = time * .00005;
		curve.getPointAt( carTime % 1, carPosition );
		curve.getPointAt( ( carTime + 0.01 ) % 1, carTarget );
		car.position.set( carPosition.x, 2, carPosition.y );
		car.lookAt( carTarget.x, 2, carTarget.y );
        carCamera.lookAt(carTarget.x, 2, carTarget.y);

        if (!isCarCamera) {
            renderer.render( scene, camera);
        } else {
            renderer.render( scene, carCamera );
        }
        requestAnimationFrame( render );
    }
    requestAnimationFrame( render );

    document.addEventListener('keydown', function(event) {
        if (event.key === 's') {
            event.preventDefault(); // 阻止默认行为（如保存页面）
            isCarCamera = !isCarCamera;
        }
    });
});
</script>

<style scoped>
</style>